* Save temp file of preference data dropping outside options
clear
use ${data}preference_data.dta
drop if outside_cm==1 | outside_sch==1
keep if intDay==firstDay
tempfile pref_data
save `pref_data'


quietly {

* School and teacher utilities and outside options
clear
gen bs = .
gen d = .
forv bs=0/$bootstraps {
	forv d=1/3 {
		append using ${data}Simulation/sim_data_d`d'_bs`bs'.dta
		replace bs = `bs' if missing(bs)
		replace d = `d' if missing(d)
	}
}
tempfile draws
save `draws'
		
	forv bs=0/$bootstraps {
		forv d=1/3 {
			forv o=1/10 {

				clear
				cap use ${data}Simulation/sim_fo_d`d'_o`o'_bs`bs'.dta
				
				if _rc==0 {

				merge 1:1 teacher_id schoolpos_id  using ${data}Simulation/sim_multi_d`d'_o`o'_bs`bs'.dta, nogen assert(3) 
				
				
				keep schoolcert_id teacher_id schoolpos_id fo_match da_match da_tier_match tp_match rsd_match draft_match
				
				gen bs=`bs'
				gen d=`d'
				gen oo=`o'
				
				tempfile match_bs`bs'_d`d'_o`o'
				save `match_bs`bs'_d`d'_o`o''
				}
			}
		}
	}
 
 clear
 forv bs=0/$bootstraps {
 	forv d=1/3 {
		forv o=1/10 {
			cap append using  `match_bs`bs'_d`d'_o`o''
			
		}
	}
 }
 tempfile matches
 save `matches'
 
 }
 
 clear
 use `draws'
 
 * Bring in matches
 merge 1:1 bs d oo teacher_id schoolpos_id using `matches',  nogen assert(1 3)
 

 
* Bring in teacher and school characteristics
 merge m:1 teacher_id schoolcert_id using `pref_data',   nogen assert(3)
 



 gen acceptable = u_t_oo_mid>outside_t

bys teacher_id bs oo: egen cm_seq=seq()
foreach t in fo da tp da_tier rsd draft {
	gen rank_cm_`t' = Rank_CM_true_oo_mid if `t'_match==1
	gen rank_school_`t' = Rank_School if `t'_match==1
	gen retain_`t' = acceptable if `t'_match==1
	gen round_`t' = round if `t'_match==1
	bys bs oo d school_id: egen sch_hire_`t' = max(`t'_match) 
	bys bs oo d school_id: egen sch_n_hires_`t' = sum(`t'_match) 
	
	bys bs oo d school_id: egen sch_rethire_`t' = max(`t'_match*acceptable) 
	bys bs oo d school_id: egen sch_n_rethires_`t' = sum(`t'_match*acceptable) 
	
	bys teacher_id bs oo: egen teacher_hire_`t' = max(`t'_match)
	replace teacher_hire_`t' = . if cm_seq!=1
	
}

drop cm_seq


 save ${data}simulation_results.dta, replace 
 
exit 
 

	